//
//  OMDraft.m
//  Weibbo
//
//  Created by ifuninfo on 13-6-9.
//  Copyright (c) 2013年 Omnivores. All rights reserved.
//

#import "OMDraft.h"
#import "SynthesizeSingleton.h"
@implementation OMDraft
SYNTHESIZE_SINGLETON_FOR_CLASS(OMDraft)
- (id)init
{
    self = [super init];
    if (self)
    {
        _draftList = [WBBData draftList];
    }
    return self;
}
+(OMDraft *)sharedDraft
{
    return [OMDraft sharedOMDraft];
}
-(int)count
{
    return [_draftList count];
}
- (DraftEntity *)draftAtIndex:(int)index
{
    if (index >= [self count]) {
        return nil;
    }
    DraftEntity  *entity = [[DraftEntity alloc] initWithInfo:[_draftList objectAtIndex:index]];
    return UIAutoRelease(entity);
}
- (void)insertDraft:(DraftEntity *)draft
{
    NSDictionary *dic = [draft toDictionary];
    [_draftList insertObject:dic atIndex:0];
    [WBBData save];
}
- (void)addDraft:(DraftEntity *)draft
{
    NSDictionary *dic = [draft toDictionary];
    [_draftList addObject:dic];
    [WBBData save];
}
- (void)removeDraft:(DraftEntity *)draft
{
    for (int i = 0; i < [self count]; i++)
    {
        DraftEntity *entity = [self draftAtIndex:i];
        if ([entity.entityId isEqualToString:draft.entityId])
        {
            [self removeDraftByIndex:i];
            break;
        }
    }
}
- (void)removeDraftByIndex:(int)index
{
    [_draftList removeObjectAtIndex:index];
    [WBBData save];
}

- (NSString *)description{
    return [_draftList description];
}
- (int)indexOfEntity:(DraftEntity *)draft
{
    int i = 0;
    for (NSDictionary *dic in _draftList)
    {
        NSString  *eId = [dic objectForKey:@"id"];
        if ([eId isEqualToString:draft.entityId]) {
            return i;
        }
        i ++;
    }
    return INT16_MAX;
}

- (void)replaceDraft:(DraftEntity *)draft index:(int)index
{
    NSDictionary *dic = [draft toDictionary];
    [_draftList replaceObjectAtIndex:index withObject:dic];
    [WBBData save];
}
@end
